package com.wing.user.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.user.model.entity.Authority;
import com.wing.user.model.response.AuthorityVO;
import com.wing.user.model.response.RoleAuthorityVO;
import com.wing.user.service.AuthorityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author
 */
@Api(value = "Admin-权限管理", tags = "#/user/authority")
@RestController
@RequestMapping("/user/admin/authority")
@RequiredArgsConstructor
public class AuthorityController {

    private final AuthorityService authorityService;

    @ApiOperation(value = "查询所有权限", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<Authority> list(Integer page, Integer limit, String keyword) {
        LambdaQueryWrapper<Authority> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)) {
            lambdaQueryWrapper
                .like(Authority::getAuthority, keyword)
                .or()
                .like(Authority::getAuthorityName, keyword)
                .or()
                .like(Authority::getPageUrl, keyword);
        }
        IPage<Authority> pageResult = authorityService.page(new Page<>(page, limit), lambdaQueryWrapper);
        // 筛选结果
//        if (keyword != null && !keyword.trim().isEmpty()) {
//            keyword = keyword.trim();
//            Iterator<Authority> iterator = pageResult.getRecords().iterator();
//            while (iterator.hasNext()) {
//                Authority next = iterator.next();
//                boolean b = (next.getAuthorityName() != null && next.getAuthorityName().contains(keyword)) || (next.getPageUrl() != null && next.getPageUrl().contains(keyword)) || (next.getAuthority() != null && next.getAuthority().contains(keyword));
//                if (!b) {
//                    iterator.remove();
//                }
//            }
//        }
        return new PageResult<>(pageResult.getRecords(), pageResult.getTotal());
    }

    @ApiOperation(value = "查询权限", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String", paramType = "query")
    })
    @GetMapping("/listByUserId")
    public JsonResult<List<AuthorityVO>> listByUserId(Long userId) {
        return JsonResult.success(authorityService.listByUserId(userId));
    }

    @ApiOperation(value = "同步权限", notes = "同步")
    @PostMapping("/sync")
    public JsonResult sync() {
        authorityService.sync();
        return JsonResult.success("同步成功");
    }

    @ApiOperation(value = "刷新权限缓存")
    @GetMapping("/authorityRoleList")
    public JsonResult<List<RoleAuthorityVO>> authorityRoleList() {
        List<RoleAuthorityVO> roleAuthorityVOList = authorityService.authorityRoleList();
        return JsonResult.success(roleAuthorityVOList);
    }

    /**
     * 生成权限、菜单并且设置给相关角色添加对应权限
     */
    @GetMapping("/generateData")
    public JsonResult generateData(String newAuthoritys, String newNames, String lastAuthoritys, String sorts, String updMenuNames){
        try {
            if(authorityService.generateData(newAuthoritys, newNames, lastAuthoritys, sorts, updMenuNames)){
                return JsonResult.success("生成数据成功");
            }else{
                return JsonResult.fail("生成数据失败");
            }
        } catch (BusinessException e) {
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return JsonResult.fail(e.getMessage());
        }
    }

}
